package com.rstrulak.managedBeans.controllers;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.rstrulak.dao.ContextDao;
import com.rstrulak.dao.ProjectDao;
import com.rstrulak.dao.TaskAttachmentsDao;
import com.rstrulak.dao.TaskDao;
import com.rstrulak.dao.UserDao;
import com.rstrulak.model.Context;
import com.rstrulak.model.Project;
import com.rstrulak.model.Task;
import com.rstrulak.model.TaskAttachments;
import com.rstrulak.model.User;
import com.rstrulak.utils.Constants;
import com.rstrulak.utils.JSFUtils;
import com.rstrulak.utils.NoteFile;

@Component("newTasktBean")
@Scope("request")
public class NewTaskBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -945358760825549817L;

	@Autowired
	private ProjectDao projectDao;

	@Autowired
	UserDao userDao;

	@Autowired
	TaskDao taskDao;

	@Autowired
	ContextDao contextDao;

	@Autowired
	private TaskAttachmentsDao taskAttachmentsDao;

	private Task task;

	private String taskName;

	private String taskDescription;

	private Long projectId;

	private Long contextId;

	private String contextName;

	private String ownerName;

	private Map<String, Long> allContextMap;

	private Map<String, Long> allUsersMap;

	private Boolean isProjectSource = true;

	@SuppressWarnings("unused")
	private Boolean projectOwner;

	private Project projectById;

	@PostConstruct
	public void init() {
		projectId = (Long) JSFUtils.flashScope().get(Constants.PROJECT_ID);
		contextId = (Long) JSFUtils.flashScope().get(Constants.CONTEXT_ID);
		
		if(projectId == null){
			JSFUtils.setFlashFromSession();
			projectId = (Long) JSFUtils.flashScope().get(Constants.PROJECT_ID);
			JSFUtils.flashScope().put(Constants.PROJECT_ID, projectId);
		}

		if (projectId != null) {
			projectById = projectDao.getById(projectId);
			isProjectSource = true;

			allUsersMap = new HashMap<String, Long>();
			allContextMap = new HashMap<String, Long>();
			List<Context> contextList = contextDao.getAll();
			for (Context context : contextList) {
				allContextMap.put(context.getName(), context.getId());
			}

			if (JSFUtils.getLoggedUser().getId().equals(projectDao.getById(projectId).getOwner().getId())) {
				List<User> allUsers = userDao.getAll();

				for (User user : allUsers) {
					allUsersMap.put(user.getFirstName() + " " + user.getLastName(), user.getId());
				}
			}

			// potencjalnie niebezpieczny dla flashscope
			JSFUtils.flashScope().put(Constants.CONTEXT_ID, contextId);
			//
			JSFUtils.flashScope().put(Constants.PROJECT_ID, projectId);
		} else if (contextId != null) {
			isProjectSource = false;
			JSFUtils.flashScope().put(Constants.CONTEXT_ID, contextId);
		}
	}

	@PreDestroy
	public void destroy() {
		JSFUtils.flashScope().put(Constants.PROJECT_ID, projectId);
	}

	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	public String getTaskDescription() {
		return taskDescription;
	}

	public void setTaskDescription(String taskDescription) {
		this.taskDescription = taskDescription;
	}

	public Map<String, Long> getAllContextMap() {
		return allContextMap;
	}

	public void setAllContextMap(Map<String, Long> allContextMap) {
		this.allContextMap = allContextMap;
	}

	public String getContextName() {
		return contextName;
	}

	public void setContextName(String contextName) {
		this.contextName = contextName;
	}

	public String getOwnerName() {
		return ownerName;
	}

	public void setOwnerName(String ownerName) {
		this.ownerName = ownerName;
	}

	public Boolean getProjectOwner() {
		return JSFUtils.getLoggedUser().getId().equals(projectById.getOwner().getId());
	}

	public void setProjectOwner(Boolean projectOwner) {
		this.projectOwner = projectOwner;
	}

	public Map<String, Long> getAllUsersMap() {
		return allUsersMap;
	}

	public void setAllUsersMap(Map<String, Long> allUsersMap) {
		this.allUsersMap = allUsersMap;
	}

	public void saveTask(FileUploadBean fileUploadBean) throws ServletException, IOException {
		task = new Task();
		task.setTaskName(taskName);
		task.setTaskDescription(taskDescription);
		task.setOwner(JSFUtils.getLoggedUser());
		if (projectId != null) {
			task.setProject(projectById);
			if (contextName != null) {
				task.setContext(contextDao.getById(new Long(contextName)));
			}
			if (JSFUtils.getLoggedUser().getId().equals(projectById.getOwner().getId()) && ownerName != null) {
				task.setOwner(userDao.getById(new Long(ownerName)));
			} else if (!JSFUtils.getLoggedUser().getId().equals(projectById.getOwner().getId())) {
				task.setOwner(JSFUtils.getLoggedUser());
			}
		}
		if (contextId != null) {
			task.setContext(contextDao.getById(contextId));
		}
		Long taskId = taskDao.save(task);

		FileUploadBean uploadBean = fileUploadBean;
		ArrayList<NoteFile> filesArray = uploadBean.getFiles();
		List<TaskAttachments> taskAttachmentsList = new ArrayList<TaskAttachments>();

		for (int i = 0; i < filesArray.size(); i++) {
			TaskAttachments taskAttachments = new TaskAttachments();
			String oldName = filesArray.get(i).getName();
			StringBuilder finalName = new StringBuilder();
			finalName.append("taskId_");
			finalName.append(taskId);
			finalName.append("_fileName_");
			finalName.append(oldName);

			taskAttachments.setTask(task);
			taskAttachments.setFilePath(Constants.TASK_ATTACHMENTS_PATH + finalName);
			taskAttachments.setFileName(oldName);
			taskAttachmentsList.add(taskAttachments);

			filesArray.get(i).setName(finalName.toString());
		}

		fileUploadBean.saveTaskFiles();
		fileUploadBean.clearUploadData();
		if (taskAttachmentsList.size() > 0) {
			this.saveTaskAttachments(taskAttachmentsList);
		}

		if (isProjectSource) {
			JSFUtils.redirect("/protected/projectDetails.xhtml");
		} else if (!isProjectSource) {
			JSFUtils.redirect("/protected/contextDetails.xhtml");
		}
	}

	public void cancelAddTask(FileUploadBean fileUploadBean) throws ServletException, IOException {
		fileUploadBean.clearUploadData();
		if (isProjectSource) {
			JSFUtils.redirect("/protected/projectDetails.xhtml");
		} else if (!isProjectSource) {
			JSFUtils.redirect("/protected/contextDetails.xhtml");
		}
	}

	public void saveTaskAttachments(List<TaskAttachments> taskAttachmentsList) {
		for (TaskAttachments taskAttachments : taskAttachmentsList) {
			taskAttachmentsDao.save(taskAttachments);
		}
	}

}
